<template>
  <a-card title="设备查询" :bordered="false" class="condition-card">
    <div class="condition-row">
      <div class="condition-col flex align-center">
        <a-input allow-clear placeholder="请输入设备名称" v-model:value="conditionState.name"></a-input>
        <a-button class="ml-12" type="primary" :loading="searchLoading" @click="handleSearch">查询</a-button>
      </div>
    </div>
  </a-card>
  <a-card title="设备列表" :bordered="false" class="result-card mt-20">
    <template #extra>
      <a-button type="primary" @click="handlePopCreateModal">添加设备</a-button>
    </template>
    <a-table :columns="columns" :data-source="deviceList" :pagination="false" :scroll="{y: 'calc(100vh - 405px)'}">
      <template #bodyCell="{record, column}">
        <template v-if="column.dataIndex === 'option'">
          <a-button type="link" @click="handlePopEditModal(record)">
            <i class="iconfont icon-bianji"></i>
          </a-button>
          <a-button class="ml-12" type="link" @click="handlePopQrcodeModal(record)">
            <i class="iconfont icon-erweima"></i>
          </a-button>
          <a-popconfirm
              title="确定要删除吗?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="handleDelRecord(record)">
            <a-button class="ml-12" type="link" danger>
              <i class="iconfont icon-shanchu"></i>
            </a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>
    <div class="pagination-content flex justify-end">
      <a-pagination v-model:current="conditionState.page" show-quick-jumper show-size-changer :show-total="total => `共 ${total} 条`" :total="total" v-model:pageSize="conditionState.size" @change="handlePageChange" />
    </div>
  </a-card>
  <a-modal :width="520" :title="editMode ? '编辑设备信息' : '添加设备信息'" v-model:visible="modalVisible" :confirmLoading="saveLoading" @ok="handleSave">
    <a-form
        layout="vertical"
        :model="formState"
        :rules="rules"
        ref="deviceForm">
      <a-form-item
          label="设备编号"
          name="bianhao">
        <a-input v-model:value="formState.bianhao" placeholder="请输入设备编号"></a-input>
      </a-form-item>
      <a-form-item
          label="设备名称"
          name="name">
        <a-input v-model:value="formState.name" placeholder="请输入设备名称"></a-input>
      </a-form-item>
      <a-form-item
          label="所属网点"
          name="wdCode">
        <a-select v-model:value="formState.wdCode" @change="handleShopChange">
          <a-select-option v-for="shop in shopList" :key="shop.id" :value="shop.wdCode">{{shop.wdname}}</a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
  <a-modal title="设备二维码" :width="400" v-model:visible="qrcodeModalVisible" :footer="null">
    <div class="qrcode-content flex justify-center align-center">
      <span class="device-info">{{currentFormItem.bianhao}}-{{currentFormItem.wangdian}}</span>
      <div class="qrcode-img" :style="{'background-image': 'url(' + qrcodeUrl + ')'}"></div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import {nextTick, reactive, ref} from "vue";
import api from '../../api/device'
import merchant from '../../api/merchant'
import {DeviceItem, ShopItem} from '../../types/common'
import {uuid} from '../../common/utils'
import {message} from "ant-design-vue";
const modalVisible = ref<boolean>(false)
const editMode = ref<boolean>(false)
const qrcodeModalVisible = ref<boolean>(false)
const defFormState = {
  "address": "",
  "bianhao": "",
  "name": "",
  "wangdian": "",
  "wdCode": ""
}
const currentFormItem = ref()
const formState = ref({...defFormState})
const deviceForm = ref()
const rules = {
  name: [
    { required: true, trigger: 'blur', message: '请输入设备名称' },
  ],
  wdCode: [
    { required: true, trigger: 'change', message: '请选择网点' },
  ],
}
const searchLoading = ref<boolean>(false)
const saveLoading = ref<boolean>(false)
const conditionState = reactive({
  name: '',
  page: 1,
  size: 10,
})
const total = ref<number>(0)
const deviceList = ref<DeviceItem[]>([])
const columns = [
  {
    dataIndex: 'name',
    key: 'name',
    title: '设备名称',
  },{
    dataIndex: 'bianhao',
    key: 'bianhao',
    title: '设备编号',
  },{
    dataIndex: 'wangdian',
    key: 'wangdian',
    title: '网点名称',
  },{
    dataIndex: 'wdCode',
    key: 'wdCode',
    title: '网点编号',
  },{
    dataIndex: 'address',
    key: 'address',
    title: '地址',
  },{
    dataIndex: 'option',
    key: 'option',
    title: '操作',
  },
]
const getPageData = async () => {
  searchLoading.value = true
  deviceList.value = []
  try {
    const res = await api.getList({
      name: conditionState.name || '',
      page: conditionState.page - 1,
      size: conditionState.size,
    })
    searchLoading.value = false
    if (res.content) {
      total.value = res.content.total || 0
      if (res.content.content && res.content.content.length) {
        deviceList.value = res.content.content
      }
    }
  } catch(e: any) {
    searchLoading.value = false
  }

}
const shopList = ref<ShopItem[]>([])
const getShopPageData = async () => {
  shopList.value = []
  try {
    const res = await merchant.getList({
      name: conditionState.name || '',
      page: 0,
      size: 999,
    })
    if (res.content) {
      if (res.content.content && res.content.content.length) {
        shopList.value = res.content.content
      }
    }
  } catch(e: any) {
  }
}
const handleShopChange = (v: number, opt: any) => {
  const item: ShopItem = shopList.value.find((shop: ShopItem) => shop.id === opt.key)
  if (item) {
    formState.value.wangdian = item.wdname
    formState.value.address = item.wdaddress
  }
}
const handleSearch = () => {
  conditionState.page = 1
  total.value = 0
  getPageData()
}
const handlePageChange = (page: number, pageSize: number) => {
  if (pageSize !== conditionState.size) {
    conditionState.page = 1
  }
  getPageData()
}
getShopPageData()
handleSearch()
const handleSave = async () => {
  try {
    await deviceForm.value.validateFields()
    console.log('formState', formState.value)
    saveLoading.value = true
    let res
    if (!editMode.value) {
      res = await api.create(formState.value)
    } else {
      res = await api.edit(formState.value)
    }
    saveLoading.value = false
    if (res.success) {
      if (!editMode.value) {
        message.success('设备添加成功')
        handleSearch()
      } else {
        message.success('设备修改成功')
        Object.assign(currentFormItem.value, formState.value)
      }
      modalVisible.value = false
    } else {
      let msg = '操作失败'
      if (res.errors && res.errors[0] && res.errors[0].message) {
        msg = res.errors[0].message
      }
      message.error(msg)
    }
  }catch(e){
    saveLoading.value = false
    if (e.errors && e.errors[0] && e.errors[0].message) {
      message.error(e.errors[0].message)
    }
    console.log(e)
  }
}
const handlePopCreateModal = () => {
  formState.value = {...defFormState}
  formState.value.bianhao = uuid(12, 0, '0123456789')
  editMode.value = false;
  modalVisible.value = true
  nextTick(() => {
    deviceForm.value.clearValidate()
  })
}
const handlePopEditModal = (item: any) => {
  currentFormItem.value = item
  Object.assign(formState.value, item)
  editMode.value = true;
  modalVisible.value = true
  nextTick(() => {
    deviceForm.value.clearValidate()
  })
}
const handleDelRecord = async (item: any) => {
  try {
    const res = await api.del(item.id)
    if (res.success) {
      message.success('删除成功')
      handleSearch()
    } else {
      let msg = '操作失败'
      if (res.errors && res.errors[0] && res.errors[0].message) {
        msg = res.errors[0].message
      }
      message.error(msg)
    }
  } catch (e) {
    if (e.errors && e.errors[0] && e.errors[0].message) {
      message.error(e.errors[0].message)
    }
    console.log(e)
  }
}

const qrcodeUrl = ref('')
const handlePopQrcodeModal = (device: DeviceItem) => {
  currentFormItem.value = device
  qrcodeUrl.value = ''
  qrcodeModalVisible.value = true
  api.qrcode(device.bianhao).then((data) => {
    const blob = new Blob([data], { type: 'image/png' })
    const imageUrl = (window.URL || window.webkitURL).createObjectURL(blob)
    qrcodeUrl.value = imageUrl;
  })
}
</script>

<style scoped lang="less">
.qrcode-content{
  flex-direction: column;
  .qrcode-img{
    width: 300px;
    height: 300px;
  }
  .device-info{
    font-weight: bold;
    font-size: 16px;
  }
}
.ant-btn-link{
  padding: 0;
}

</style>
